package com.alipay.controller;

import com.alibaba.common.lang.StringUtil;
import com.alipay.account.facade.AccountTransService;
import com.alipay.account.facade.com.alipay.account.dto.AccountDTO;
import com.alipay.model.ExceptionUtils;
import com.alipay.model.ResponseBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.ws.rs.QueryParam;
import java.util.List;


@RestController
public class AccountController {

    @Autowired
    private AccountTransService accountTransService;

    @PostMapping("/api/account")
    public ResponseEntity<?> addAccount(AccountDTO accountDTO) {
        try {
            ResponseBody body;
            String userId = accountTransService.addAccount(accountDTO.getAuthCode());
            if (StringUtil.isNotEmpty(userId)) {
                AccountDTO ret = new AccountDTO();
                ret.setUserId(userId);
                body = new ResponseBody(ret);
            }
            else
                body = new ResponseBody(500, "fail", "添加账户失败");
            return ResponseEntity.ok(body);
        }catch (Exception e){
            return ResponseEntity.ok(new ResponseBody(500, "fail", "添加账户异常 "+ ExceptionUtils.getRootCause(e).getMessage()));
        }
    }

    @GetMapping("/api/account")
    public ResponseEntity<?> getAccount(@QueryParam("userId") String userId, @QueryParam("authCode") String authCode) {
        try {
            AccountDTO accountDTO = accountTransService.getAccount(userId, authCode);
            return ResponseEntity.ok(new ResponseBody(accountDTO));
        }catch (Exception e){
            return ResponseEntity.ok(new ResponseBody(500, "fail", "查询账户信息异常 "+ExceptionUtils.getRootCause(e).getMessage()));
        }
    }

    @GetMapping("/api/accounts/all")
    public ResponseEntity<?> getAccount() {
        try {
            List<AccountDTO>  accountDTOs = accountTransService.getAllAccounts();
            return ResponseEntity.ok(new ResponseBody(accountDTOs));
        }catch (Exception e){
            return ResponseEntity.ok(new ResponseBody(500, "fail", "查询账户信息异常 "+ExceptionUtils.getRootCause(e).getMessage()));
        }
    }

}
